package cn.com.pajx.pajx_smart_platform.api;

import android.os.Build;
import android.text.TextUtils;

import androidx.annotation.RequiresApi;

import com.google.gson.Gson;

import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

import cn.com.pajx.pajx_smart_platform.BaseApp;
import cn.com.pajx.pajx_smart_platform.tools.AESUtil;
import cn.com.pajx.pajx_smart_platform.tools.AppConstant;
import cn.com.pajx.pajx_smart_platform.tools.CommonUtil;
import cn.com.pajx.pajx_smart_platform.tools.LogUtil;
import cn.com.pajx.pajx_smart_platform.tools.MD5Util;
import cn.com.pajx.pajx_smart_platform.tools.RSAUtil;
import cn.com.pajx.pajx_smart_platform.tools.SharePreferencesUtil;


/**
 * create by ruancw on 2023/04/03
 * description 公共参数封装
 */
class HttpParamsUtil {
    private static final String app_key = "9511bd681d8243368191f19060a5eb67";

    /**
     * 生成带有sign的map
     * timestamp（当前时间戳）、token（访问令牌）、app_id(绑定关系ID,没有则传0)；
     */
    static LinkedHashMap<String, String> addSignToMap(LinkedHashMap<String, String> map) {
        String app_id = "Api.APP_ID";
        String app_version = CommonUtil.getVersionName(BaseApp.getInstance());
        String token = SharePreferencesUtil.getInstance().getString(AppConstant.LOGIN_TOKEN);
        //判断app_id
        if (!map.containsKey("app_id")) {
            if (TextUtils.isEmpty(app_id)) {
                app_id = "0";
            }
            map.put("app_id", app_id);
        }
        //判断token
        if (!map.containsKey("token")) {
            if (TextUtils.isEmpty(token)) {
                token = "";
            }
            map.put("token", token);
        }
        //版本号
        map.put("app_version", app_version);
        //时间戳
        map.put("timestamp", String.valueOf(System.currentTimeMillis() / 1000));
        //参数名按ASCII 码从小到大排序
        List<Map.Entry<String, String>> infoIds = new ArrayList<>(map.entrySet());
        Collections.sort(infoIds, new Comparator<Map.Entry<String, String>>() {
            @Override
            public int compare(Map.Entry<String, String> o1, Map.Entry<String, String> o2) {
                return (o1.getKey()).compareTo(o2.getKey());
            }
        });
        //参数名及参数拼接
        StringBuilder params = new StringBuilder();
        for (int n = 0; n < infoIds.size(); n++) {
            Map.Entry<String, String> entry = infoIds.get(n);
            //处理 key value
            String key = entry.getKey();
            String value = entry.getValue();

            if (TextUtils.isEmpty(value)) {
                value = "";
                map.put(key, value);
            }
            //处理[]
            if (key.contains("[") && key.contains("]")) {
                //处理
                key = key.substring(0, key.indexOf("["));
            }
            params.append(key);
            params.append("=");
            params.append(value);
        }
        String params_value = params + app_key;
        map.put("sign", MD5Util.MD5(params_value));
        return map;

    }

    /**
     * 将map参数集合转换成json
     * @param map map参数集合
     * @return json字符串
     */
    static String paramsToJson(LinkedHashMap<String,String> map){
        Gson gson = new Gson();
        return gson.toJson(addSignToMap(map));
    }

    /**
     * 生成json形式的body
     * @param data data参数
     * @return 字符串
     */
    @RequiresApi(api = Build.VERSION_CODES.KITKAT)
    static LinkedHashMap<String,String> generateBodyJson(String data) {
        LogUtil.e("data="+data);
        try {
            String encrypt_key = RSAUtil.encryptByPublicKey(RSAUtil.loadPublicKeyByStr("AppConfig.RSA_PUBLIC"), "AppConfig.AES_KEY".getBytes());
            String encrypt_data = AESUtil.encrypt("AppConfig.AES_KEY", data);
            LinkedHashMap<String, String> map = new LinkedHashMap<>();
            map.put("app_id", "AppConfig.APP_ID");
            map.put("encrypt_key", URLEncoder.encode(encrypt_key));
            map.put("data", URLEncoder.encode(encrypt_data));
            return map;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
}
